package com.base.myproject.client.HR.recruitment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.BaseTabPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseComboBoxX;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;

/**
 * @author cxghiu4102@gmail.com 2010-11-18 安排复试
 * 
 */
public class Retest extends BaseJDBCPanel {
	private TextField<String> interviewNo = new TextField<String>();  //面试编号
	private BaseComboBoxForm<BaseModelData> sysmem = new BaseComboBoxForm<BaseModelData>(
			"id", "name", "systeminfo",
			"where len(id)=(select max(len(id)) from systeminfo)", true);  //面试部门
	private DateField start = new DateField();  //面试开始时间段
	private DateField end = new DateField();  //面试结束时间段
	private BaseComboBoxX retest = new BaseComboBoxX("name", "dictionary",
			"where type='retest'");  //想进行的操作（其实也是查询不同的记录和结果了）

	private Button search = new Button("查询");
	private Button throuth = new Button("批量通过");
	private Button noThrouth = new Button("批量不通过");
	
	private String sql = "select a.* from hr_interview a inner join (select positionRequestId,max(number) as m "
		+ "from hr_interview group by positionRequestId) b on a.positionRequestId=b.positionRequestId "
		+ "and a.number = b.m where isThrough = '1'" ;  //页面打开时默认显示的数据的sql，显示所有最后一次面试，并通过面试的记录

	private List<String> validation = new ArrayList<String>();  //用于保存想录用的职位编号，并验证所有想录用的职位所对应
															//在职位申请表是唯一的

	public Retest() {
		retest.setEditable(false);
		init();
	}

	public void init() {
		start.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		end.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		search.addListener(Events.OnClick, getListener());
		throuth.addListener(Events.OnClick, getListener());
		noThrouth.addListener(Events.OnClick, getListener());
		initwidget();
		registerMainStore(store);
	}

	private void initwidget() {
		BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH,
				150);
		southData.setCollapsible(true);
		southData.setFloatable(true);
		southData.setSplit(true);
		southData.setMargins(new Margins(0, 5, 0, 5));

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 5, 5));

		VerticalPanel vp = new VerticalPanel();
		HorizontalPanel hp = new HorizontalPanel();

		hp.add(search);
		hp.add(throuth);
		hp.add(noThrouth);

		vp.setSpacing(5);
		vp.add(getForm());
		vp.add(hp);
		vp.add(createGrid());

		ContentPanel content = new ContentPanel();
		content.setScrollMode(Scroll.AUTO);
		content.setHeaderVisible(false);
		content.add(vp);

		ContentPanel south = new ContentPanel();
		south.setHeading("被面试人员资料");
		south.add(createForm());

		add(content, centerData);
		add(south, southData);
	}

	private FormPanel getForm() {
		FormPanel form = new FormPanel();
		TableLayout tl = new TableLayout(10);
		form.setBodyBorder(false);
		form.setPadding(4);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);

		form.setLayout(tl);
		form.setHeaderVisible(false);

		form.add(new Label("面试编号："));
		interviewNo.setWidth(127);
		form.add(interviewNo);
		form.add(new Label("面试部门："));
		sysmem.setWidth(100);
		form.add(sysmem);
		form.add(new Label("面试时间从："));
		start.setWidth(127);
		form.add(start);
		form.add(new Label("到："));
		end.setWidth(127);
		form.add(end);
		form.add(new Label("操作："));
		retest.setWidth(100);
		form.add(retest);

		return form;
	}

	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("interviewNo");
		type.getField("interviewNo").setType(String.class);
		type.addField("depCode");
		type.getField("depCode").setType(String.class);
		type.addField("positionRequestId");
		type.getField("positionRequestId").setType(Long.class);
		type.addField("interviewPeopleId");
		type.getField("interviewPeopleId").setType(String.class);
		type.addField("interviewDate");
		type.getField("interviewDate").setType(Date.class);
		type.addField("place");
		type.getField("place").setType(String.class);
		type.addField("number");
		type.getField("number").setType(Integer.class);
		type.addField("isThrough");
		type.getField("isThrough").setType(Boolean.class);
		type.addField("explain");
		type.getField("explain").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_interview");
		info.setKeyname(new String[] { "icode" });
		info
				.setSql(sql);
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}

	BaseGrid<BusiObject> grid = null;
	CheckBoxSelectionModel<BusiObject> cbs;

	BaseGrid<BusiObject> createGrid() {
		cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C2 = new ColumnConfig("interviewNo", "面试编号", 100);
		columns.add(C2);
		ColumnConfig C3 = new ColumnConfig("depCode", "面试部门", 80);
		BaseComboBoxForm<BaseModelData> C_num4 = new BaseComboBoxForm<BaseModelData>(
				"id", "name", "systeminfo",
				"where len(id)=(select max(len(id)) from systeminfo)", true);
		C3.setRenderer(C_num4);
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("positionRequestId", "申请表编号", 80);
		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("interviewPeopleId", "面试人员", 80);
		BaseComboBoxForm<BaseModelData> C_num5 = new BaseComboBoxForm<BaseModelData>(
				"bcode", "bname", "bcode", "", true);
		C5.setRenderer(C_num5);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("interviewDate", "面试时间", 120);
		C6.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd HH:mm"));
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("place", "面试地点", 80);
		columns.add(C7);
		ColumnConfig C8 = new ColumnConfig("number", "面试次数", 80);
		columns.add(C8);
		CheckColumnConfig C9 = new CheckColumnConfig("isThrough", "是否通过", 60);
		C9.setEditor(new CellEditor(new CheckBox()));
		columns.add(C9);
		ColumnConfig C11 = new ColumnConfig("explain", "说明", 260);
		TextField<String> tx = new TextField<String>();
		C11.setEditor(new CellEditor(tx));
		columns.add(C11);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(getStore(), cm, false, false);
		grid.setHeight(420);
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid.setSelectionModel(cbs);
		grid.addPlugin(cbs);
		return grid;
	}

	BaseStore<BusiObject> libraryStore = null;

	BaseStore<BusiObject> getlibraryStore() {
		if (libraryStore == null) {
			createlibraryStore();
		}
		return libraryStore;
	}

	BaseStore<BusiObject> createlibraryStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("name");
		type.getField("name").setType(String.class);
		type.addField("education");
		type.getField("education").setType(String.class);
		type.addField("experience");
		type.getField("experience").setType(String.class);
		type.addField("position");
		type.getField("position").setType(String.class);
		type.addField("salary");
		type.getField("salary").setType(Double.class);
		type.addField("skills");
		type.getField("skills").setType(String.class);

		StoreInfo info = new StoreInfo();
		info.setTablename("null");
		info.setKeyname(new String[] { "icode" });
		info
				.setSql("select position,name,education,experience,salary,skills,hr_positionRequest.icode " +
						"from hr_resumeLibrary,hr_positionRequest where hr_positionRequest.resumeLibraryId" +
						"=hr_resumeLibrary.icode and hr_positionRequest.icode={positionRequestId}");
		//这个用于查出参加面试的申请表所对应的简历信息
		info.setParent(store);// 关联主表
		info.setLinkparentcolumns(new String[] { "positionRequestId" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "icode" });// 关联主表字段
		libraryStore = new BaseStore<BusiObject>(type, info);
		return libraryStore;
	}

	BaseFormPanel form = null;

	BaseFormPanel createForm() {
		BaseFormPanel form = new BaseFormPanel(getlibraryStore());
		TableLayout tl = new TableLayout(6);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);

		form.add(new Label("申请人:"), td);
		TextField<String> C_num4 = new TextField<String>();
		C_num4.setName("name");
		C_num4.setReadOnly(true);
		form.add(C_num4, td);
		form.add(new Label("申请职位:"), td);
		TextField<String> C_num9 = new TextField<String>();
		C_num9.setReadOnly(true);
		C_num9.setName("position");
		form.add(C_num9, td);
		form.add(new Label("教育程度:"), td);
		TextField<String> C_num5 = new TextField<String>();
		C_num5.setReadOnly(true);
		C_num5.setName("education");
		form.add(C_num5, td);
		form.add(new Label("工作年限:"), td);
		TextField<String> C_num6 = new TextField<String>();
		C_num6.setReadOnly(true);
		C_num6.setName("experience");
		form.add(C_num6, td);
		form.add(new Label("要求薪金:"), td);
		NumberField C_num7 = new NumberField();
		C_num7.setReadOnly(true);
		C_num7.setPropertyEditorType(Double.class);
		C_num7.setName("salary");
		form.add(C_num7, td);
		form.add(new Label("技能:"), td);
		TextField<String> C_num8 = new TextField<String>();
		C_num8.setReadOnly(true);
		C_num8.setName("skills");
		form.add(C_num8, td);
		form.setBodyBorder(false);

		form.inited();
		return form;
	};

	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				try {
					if (be.getSource().equals(throuth)) {
						auditOperation(true);
					} else if (be.getSource().equals(noThrouth)) {
						auditOperation(false);
					} else {
						//查询所有最后的面试记录的sql，用于拼接后面的查询语句
						String oldSql = "select a.* from hr_interview a inner join (select positionRequestId,max(number) as m "
								+ "from hr_interview group by positionRequestId) b on a.positionRequestId=b.positionRequestId "
								+ "and a.number = b.m where 1=1";
						String whereSql = "";

						if (!interviewNo.getRawValue().equals("")) {
							whereSql = whereSql + " and interviewNo like '%25"
									+ interviewNo.getRawValue() + "%25'";
						}
						if (!sysmem.getRawValue().equals("")) {
							whereSql = whereSql + " and depCode = '"
									+ sysmem.getValue().get("code") + "'";
						}
						if (!start.getRawValue().equals("")) {
							whereSql = whereSql + " and interviewDate >= '"
									+ start.getRawValue() + "'";
						}
						if (!end.getRawValue().equals("")) {
							whereSql = whereSql + " and interviewDate <= '"
									+ end.getRawValue() + "'";
						}
						if (retest.getRawValue().equals("填写结果")) {
							whereSql = whereSql + " and isThrough is null";
						} else {
							oldSql = "select * from hr_interview where 1=1";
						}

						String sql = oldSql + whereSql;
						String sql1 = store.getStoreinfo().getSql();
						store.getStoreinfo().setSql(sql);
						store.reload();
						store.getStoreinfo().setSql(sql1);
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

		};
		return defaultlistener;
	}

	/**
	 * @param isThrough
	 *            审核的结果（通过还是不通过）
	 *            审核结果如果为不通过的，一起设置审核状态的值。如果审核通过的，先通过发送RPC得到最大的申请表编号，
	 *            再循环设置审核状态的值和申请表编号
	 */
	public void auditOperation(final boolean isThrough) {
		if (grid.getSelectionModel()
				.getSelectedItems().size() == 0) {
			MessageBox.alert("提示",
					"请选择一个以上的申请表进行操作，谢谢!", null);
		}
		if (isThrough) {
			for (BusiObject md : grid.getSelectionModel().getSelectedItems()) {
				int index = grid.getStore().indexOf(md);
				grid.setValue(index, "isThrough", true);
			}
			save();
			cbs.deselectAll();
		} else {
			for (BusiObject md : grid.getSelectionModel().getSelectedItems()) {
				int index = grid.getStore().indexOf(md);
				grid.setValue(index, "isThrough", true);
				grid.setValue(index, "isThrough", false);
			}
			save();
			cbs.deselectAll();
		}
	}

	/**
	 * @param lists
	 *            要执行的update语句
	 * @return 执行成功与否 执行所有的update语句，更新所有已经完成招聘的人力申请表,并跳出申请表操作界面
	 * 让用户填写录用情况
	 */
	/*
	public boolean updateRequest(final List<String> lists) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		for (String sql : lists) {
			csql.getV().add(sql);
		}
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								Info.display("提示信息", "该次对" + lists.size()
										+ "个职位申请录用成功");
								String sqlNo = "";
								for (String no : validation) {
									sqlNo = sqlNo + "'" + no + "',";
								}
								sqlNo = sqlNo.substring(0, sqlNo.length() - 1);
								String sql = "select * from hr_recruitmentRequest where requestNo in ("
										+ sqlNo + ") order by requestDate asc";
								RecruitmentAudit audit = new RecruitmentAudit(
										sql) {
									void set_grid(String id) {
										
									}
								};
								audit.bt1.setEnabled(false);
								audit.bt2.setEnabled(false);
								audit.request.setEnabled(false);
								audit.seach_bt.setEnabled(false);
								audit.complete();
								BaseTabPanel.getInstance().addTab("修改录用信息",
										audit);
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);

							}
						}
					});
		}
		return true;
	}*/

}
